package com.lw.leetcode.str.b;

/**
 * 6. Z 字形变换
 *
 * @Author liw
 * @Date 2021/9/21 18:02
 * @Version 1.0
 */
public class Convert {
    public String convert(String s, int numRows) {
        if (s == null) {
            return null;
        }
        int length = s.length();
        if (length < 2) {
            return s;
        }
        if (numRows == 1) {
            return s;
        }
        byte[] bytes = s.getBytes();
        int sum = 2 * numRows - 2;
        int l2 = (length / 2 + 1);
        Byte[][] bs = new Byte[numRows][l2];
        int count = 0;
        int i = 0;
        int j = 0;
        int w = 0;
        for (byte aByte : bytes) {
            if (count < numRows) {
                i = count;
                j = w;
            } else {
                i = sum - count;
                j = count - numRows + 1 + w;
            }
            count++;
            if (count > sum - 1) {
                count = 0;
                w = numRows + w - 1;
            }
            bs[i][j] = aByte;
        }
        byte[] a = new byte[length];
        i = 0;
        for (Byte[] b : bs) {
            for (Byte b1 : b) {
                if (b1 != null) {
                    a[i++] = b1;
                }
            }
        }
        return new String(a);
    }
}
